/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package assignmentbuilder;


import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;


/**
 *
 * @author keith
 */
public class AssignmentZipBuilder {

  private Set<ContentFile> content = new TreeSet<ContentFile>();


  public AssignmentZipBuilder() {
  }


  public AssignmentZipBuilder( Collection<ContentFile> f ) {
    addContentFile( f );
  }


  final public void addContentFile( ContentFile f ) {
    content.add( f );
  }


  final public void addContentFile( Collection<ContentFile> f ) {
    content.addAll( f );
  }


  public void addContentFile( ContentFile[] f ) {
    addContentFile( Arrays.asList( f ) );
  }


  public void writeZipFile( OutputStream os ) throws IOException {
    final ZipOutputStream zos = new ZipOutputStream( os );

    final Iterator<ContentFile> files = content.iterator();

    while ( files.hasNext() ) {
      final ContentFile f = files.next();

      final ZipEntry ze = new ZipEntry( f.getName() );

      zos.putNextEntry( ze );

      final byte[] fileBytes = f.getByes();

      zos.write( fileBytes );
    }
    zos.close();
  }


  public void writeZipFile( String string ) throws IOException {
    writeZipFile( new BufferedOutputStream( new FileOutputStream( string ) ) );
  }

  public byte[] getBytes(){
    byte[] bytes = null;
    try {
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      writeZipFile(baos);
      bytes = baos.toByteArray();
    } catch (IOException ex) {
      Logger.getLogger(AssignmentZipBuilder.class.getName()).log(Level.SEVERE, null, ex);
    }
    return bytes;
  }
}
